/**
 @文件名： userInfo.ts
 @来源：YongPing.Wang|2023/11/17 15:25
 @描述：用户账号信息
 **/

import { defineStore } from 'pinia'
import baseParam from '@/config/parameter/baseParam.ts'
import { type ILoginApi, type IUserLoginPam, loginApi, logoutApi } from '@/api/userApi.ts'
import { type IApi } from '@/api/types.ts'
import { layoutInfo } from '@/store/layoutInfo.ts'

export interface IUserLabel {
  userId: string
  platform: string
  tenant: string
  app: string
  appList: string
  project: string
  projectList: string
}
export interface IUserDO {
  id: string
  account: string
  pwd: string
  nickname: string
  addr: string
  phone: string
  email: string
  jobNumber: string
  status: number | null
  userLabel: IUserLabel | null
  appCodes: string[]
}
export interface IUserInfo extends IUserDO {
  url: string
  token: string
}

export const userInfo = defineStore({
  id: `${baseParam.systemDefaultPrefix}_USER_INFO`,
  state: (): IUserInfo => {
    return {
      url: '',
      token: '',
      id: '',
      account: '',
      pwd: '',
      nickname: '',
      addr: '',
      phone: '',
      email: '',
      jobNumber: '',
      status: null,
      userLabel: null,
      appCodes: [],
    }
  },
  actions: {
    // 登录
    async loginUser(data: IUserLoginPam): Promise<boolean> {
      return await loginApi(data)
        .then((res: IApi<ILoginApi>) => {
          const data = res.data
          if (data) {
            this.token = data.token
            this.url = data.url
            const userDO = data.userDO
            if (userDO) {
              this.id = userDO.id
              this.account = userDO.account
              this.pwd = userDO.pwd
              this.nickname = userDO.nickname
              this.addr = userDO.addr
              this.phone = userDO.phone
              this.email = userDO.email
              this.jobNumber = userDO.jobNumber
              this.status = userDO.status
              this.userLabel = userDO.userLabel
              this.appCodes = userDO.appCodes
            }
            return true
          } else {
            return false
          }
        })
        .catch(() => false)
    },
    // 重新获取用户信息
    async getUserDetail() {
      return []
    },
    // 退出登录
    async userLogout(): Promise<string> {
      const layoutInfoStore = layoutInfo()
      return await logoutApi().then((res: IApi<string>) => {
        this.$reset()
        layoutInfoStore.removeLayoutInfo()
        return res.data
      })
    },
  },
  persist: true,
})
